package com.lingnan.wanxiangxinxun.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingnan.wanxiangxinxun.entity.dto.query.User_queryDTO;
import com.lingnan.wanxiangxinxun.entity.po.AuthorApplication;
import com.lingnan.wanxiangxinxun.entity.po.Notice;
import com.lingnan.wanxiangxinxun.entity.po.User;
import com.lingnan.wanxiangxinxun.entity.vo.common.PageVO;
import com.lingnan.wanxiangxinxun.entity.vo.common.Result;
import com.lingnan.wanxiangxinxun.mapper.UserMapper;
import com.lingnan.wanxiangxinxun.service.INoticeService;
import com.lingnan.wanxiangxinxun.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-03-13
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private INoticeService noticeService;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public PageVO<User> getAllInPage(long current, long size) {
        Page<User> p = new Page<>(current, size);
        p.addOrder(OrderItem.desc("create_time"));   // 降序排列

        Page<User> page_MP = this.page(p);
        PageVO<User> pageVO = PageVO.of(page_MP); // 把mybatisPlus的page对象转换成自定义的pageDTO对象

        return pageVO;
    }

    @Override
    public PageVO<User> getInCondition(User_queryDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        long current = userDTO.getCurrent();
        long size = userDTO.getSize();

        Page<User> page = new Page<>(current, size); // 创建分页对象
        Page<User> page_MP = lambdaQuery()
                .eq(user.getId() != null, User::getId, user.getId())
                .like(user.getName() != null, User::getName, user.getName())
                .eq(user.getPhone() != null, User::getPhone, user.getPhone())
                .eq(user.getEmail() != null, User::getEmail, user.getEmail())
                .eq(user.getStatus() != null, User::getStatus, user.getStatus())

                .orderByDesc(User::getCreateTime)
                .page(page); // 应用分页

        return PageVO.of(page_MP);
    }


    // 登录
    @Override
    public User userSignIn(Integer id, String phone, String password) {
        if (id == null && phone == null){
            return null;
        }
        Wrapper<User> queryWrapper = lambdaQuery()
                .eq(id != null , User::getId, id)
                .eq(phone != null , User::getPhone, phone)
                .eq(User::getPassword, password)
                .getWrapper();
        return getOne(queryWrapper);
    }




    //新增作者资格申请
    @Override
    public Result addAuthorApply(AuthorApplication authorApplication) {
        //防止重复申请
        Query query = Query.query(Criteria.where("userId").is(authorApplication.getUserId()));
        List<AuthorApplication> authorApplications = mongoTemplate.find(query, AuthorApplication.class);
        if(!authorApplications.isEmpty()){
            return Result.error("请勿重复申请");
        }

        authorApplication.setCreatedAt(new Date());
        AuthorApplication aa = mongoTemplate.save(authorApplication);
        String id = aa.getId();
        if(id == null){
            return Result.error("保存失败");
        }
        return Result.success();
    }

    //审核作者申请
    @Override
    public Result verifyAuthorApply(String id, String userId, Integer type) {

        long res = 0;
        Notice notice = new Notice();
        notice.setType(2);
        notice.setSender("万象新讯官方");
        notice.setUserId(Integer.parseInt(userId));
        notice.setCreateTime(LocalDateTime.now());

        //1.通过
        if(type == 1 || type == 2){
            //1.1 修改该用户的作者状态为 1或2
            this.update().setSql("is_author = " + type).eq("id", userId).update();

            //1.2 通知作者通过了申请
            notice.setContent("您的作者申请已通过，您的作者资格为：" + (type==1 ? "个人作者" : "机构作者"));
            noticeService.addPersonalNotice(notice);

            //1.3 删除本次申请记录
            res = deleteAuthorApplication(id);
            if(res == 0){
                return Result.error("删除申请记录出错");
            }else {
                return Result.success("已通过本次申请，作者资格为：" + type);
            }
        }
        else {
            //2.1 不通过-->通知作者未通过申请
            notice.setContent("您的作者申请已被驳回");
            noticeService.addPersonalNotice(notice);

            //2.2 删除本次申请记录
            res = deleteAuthorApplication(id);
            if(res == 0){
                return Result.error("删除申请记录出错");
            }else {
                return Result.success("已拒绝本次申请");
            }
        }
    }

    //分页获取作者资格申请
    @Override
    public PageVO<AuthorApplication> getAuthorApply(long current, long size) {
        if (current < 1 || size < 1){
            return new PageVO<>();
        }

        PageVO<AuthorApplication> pageVO = new PageVO<>();

        Sort.Order SO = Sort.Order.desc("userId"); // 排序规则
        Pageable pageable = PageRequest.of((int) (current - 1), (int) size, Sort.by(SO));
        Query query = new Query().with(pageable);

        try {
            List<AuthorApplication> authorApplications = mongoTemplate.find(query, AuthorApplication.class);
            long total = mongoTemplate.count(new Query(), AuthorApplication.class);

            pageVO.setTotal(total); // 总记录数
            pageVO.setPages(total % size == 0 ? total / size : total / size + 1); // 总页数
            pageVO.setList(authorApplications); // 当前页数据

            return pageVO;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    //删除某条申请记录
    public long deleteAuthorApplication(String id){
        Criteria criteria = Criteria.where("id").is(id);
        DeleteResult res = mongoTemplate.remove(new Query().addCriteria(criteria), AuthorApplication.class);

        log.info("删除操作执行完成，影响条数：{}", res.getDeletedCount());
        return res.getDeletedCount();
    }

}
